package me.lovetcat.common.util;

import com.google.common.base.Strings;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author acat on 2017-01-12 15:13
 */
public class DateUtil {

    public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_PATTERN = "yyyy-MM-dd";

    public static final int DATETIME_LENGTH = 18;
    public static final int DATE_LENGTH = 10;

    private static SimpleDateFormat sdf;

    private static SimpleDateFormat getSdf(){
        if(sdf == null){
            sdf = new SimpleDateFormat();
        }
        return sdf;
    }

    public static Date getDate(String date, String pattern) throws ParseException {
        getSdf().applyPattern(pattern);
        return sdf.parse(date);
    }

    public static String getSystemTime(){
        getSdf().applyPattern(DATETIME_PATTERN);
        return getSdf().format(new Date());
    }

    public static String getDateTime(Date date){
        getSdf().applyPattern(DATETIME_PATTERN);
        return sdf.format(date);
    }

    public static String getDate(Date date){
        getSdf().applyPattern(DATE_PATTERN);
        return sdf.format(date);
    }

    public static Date getDate(String date) throws ParseException {
        if(Strings.isNullOrEmpty(date)){
            return null;
        }
        if(date.length() == DATETIME_LENGTH){
            return getDate(date, DATETIME_PATTERN);
        }
        if(date.length() == DATE_LENGTH){
            return getDate(date, DATE_PATTERN);
        }
        return null;
    }
}
